package com.supermap;

import com.supermap.client.NettyClient;
import com.supermap.crypto.CryproType;
import com.supermap.crypto.CryptoUtils;
import com.supermap.ipfs.IpfsClient;
import com.supermap.protocol.RpcRequest;
import io.netty.channel.ChannelFuture;

import java.util.UUID;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/4/26 16:57
 */
public class Main {

    private static String ipfsip = "172.16.168.10";
    private static String ipfsport = "5002";

    private static String backupipfsip = "172.16.168.10";
    private static String backupipfsport = "5003";

//    private static String ipfsserverip = "127.0.0.1";
    private static String ipfsserverip = "172.16.168.10";
    private static int ipfsserverport = 50010;

    public static void main(String[] args) throws Exception {

        IpfsClient ipfsClient = new IpfsClient(ipfsip, ipfsport);
        CryproType crypto = CryproType.RSA;

        /**
         * 启动client服务
         */
        NettyClient client = new NettyClient(ipfsserverip, ipfsserverport, crypto);
        client.start();

        // （单线程）ipfsClient 节点上传数据，然后备份到 ipfsbackupIp:ipfsbackupPort
        for (int i = 0; i < 50; i++) {
            //  (1)文件上传到 ipfs 返回 hashId
            String hashId = ipfsClient.upBytes(UUID.randomUUID().toString().getBytes());
            // （2）构成 RpcRequest 后发送给服务端
            RpcRequest request = new RpcRequest();
            request.setInfoPurposes("client.message");
            request.setHashId(client.encrypt(hashId));
            request.setIpfsIp(backupipfsip);
            request.setIpfsPort(backupipfsport);
            request.setPublicKey(CryptoUtils.RSAPubToString(client.getClientPublicKey()));
            ChannelFuture channelFuture = client.writeAndFlush(request);
            if (channelFuture == null) {
                System.out.println("重连失败");
            }
        }

        /**
         * tips: 必须加上（发送标志给服务端，然后客户端接收标志识别，最后客户端主动关闭客户端连接）
         */
        client.shutDownClient();
    }




}
